from django.contrib import admin

from Shop.models import Commodity, Order
from Store.models import Store
from django import forms


# Register your models here.

class CommodityForm(forms.ModelForm):
    class Meta:
        model = Commodity
        exclude = ('turnover',)


@admin.register(Commodity)
class CommodityAdmin(admin.ModelAdmin):
    list_display = (
        'name', 'category_first', 'category_second', 'original_price', 'current_price', 'stock', 'turnover',
        'store')
    list_filter = ('store', 'category_first', 'category_second')
    search_fields = ('name',)
    form = CommodityForm

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(store__user=request.user)

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "store":
            kwargs["queryset"] = Store.objects.filter(user=request.user)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)


class OrderForm(forms.ModelForm):
    STATUS_CHOICES = (
        ('待发货', '待发货'),
        ('已发货', '已发货'),
        ('已完成', '已完成'),
    )
    status_merchant = forms.ChoiceField(choices=STATUS_CHOICES, label='订单状态')
    class Meta:
        model = Order
        fields = ('status_merchant',)


@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ('id', 'get_commodity', 'address', 'created_at', 'status_buyer', 'status_merchant', 'user')
    list_filter = ('status_buyer', 'status_merchant', 'created_at',)
    ordering = ('status_buyer', 'status_merchant', 'created_at',)

    form = OrderForm
    @admin.display(description='商品')
    def get_commodity(self, obj):
        many_commodity=', '.join([commodity.name for commodity in obj.related_commodity.all()])
        return many_commodity

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(merchant=request.user)

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "related_commodity":
            kwargs["queryset"] = Commodity.objects.filter(store__user=request.user)
        return super().formfield_for_manytomany(db_field, request, **kwargs)
